package Text2;

import java.util.*;

public class Main {
    public static int m, n, N = 110;
    public static int[][] g = new int[N][N];
    public static int[][] d = new int[N][N];

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        n = scanner.nextInt();
        m = scanner.nextInt();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                g[i][j] = scanner.nextInt();
                d[i][j] = -1;
            }
        }
        d[0][0] = 0;
        System.out.println(bfs());
    }

    private static int bfs() {
        Queue<PII> q = new LinkedList<>();
        q.offer(new PII(0, 0));
        int[] dx = {-1, 0, 1, 0};//上(-1,0) 下(1,0)
        int[] dy = {0, 1, 0, -1};//左(0,-1) 右(0,1)
        while (!q.isEmpty()) {
            PII t = q.poll();
            for (int i = 0; i < 4; i++) {
                int x = t.a + dx[i];
                int y = t.b + dy[i];
                if (x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && d[x][y] == -1) {
                    d[x][y]=d[t.a][t.b]+1;
                    q.offer(new PII(x,y));
                }
            }

        }
        return d[n-1][m-1];
    }

}

class PII {
    public int a, b;

    public PII(int a, int b) {
        this.a = a;
        this.b = b;
    }
}